package com.example.beryl.proSystem;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.app.Dialog;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.example.beryl.R;
import com.example.beryl.Util.HandlePublic;
import com.example.beryl.Util.ReceiveBroadCast;
import com.example.beryl.entity.Action;
import com.example.beryl.entity.Cutting.MyListView;
import com.example.beryl.entity.UserData.Person;
import com.example.beryl.http.Net_userData;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.example.beryl.http.Net_cuttingRec;

/**
 * 裁切接收
 */
public class cuttingReceive extends AppCompatActivity {

    private ListView listView;
    private SimpleAdapter adapter;
    private Toolbar toolbar;
    private Button button;
    public ConstraintLayout clMain;
    JSONArray jsonArray = null;
    MyListView myListView = new MyListView();
    List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    private static final int CQREV = 1;
    private static final int SREV = 2;
    private static final int Pr = 3;
    public boolean mReceiverTag = false;//广播注册标志
    Net_cuttingRec dbUtil = new Net_cuttingRec();
    ReceiveBroadCast mBroadcastReceiver = new ReceiveBroadCast();
    HandlePublic handlePublic = new HandlePublic();

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        mReceiverTag = true;
        filter.addAction("com.android.server.scannerservice.broadcast"); //添加过滤条件，接收广播
        registerReceiver(mBroadcastReceiver, filter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cutting_receive);
        toolbar = findViewById(R.id.toolbar);
        button = findViewById(R.id.submit1);
        clMain = findViewById(R.id.cl_main);
        listView = findViewById(R.id.listView);
        setSupportActionBar(toolbar);
        toolbar.setTitle("裁切接收");
        toolbar.setNavigationIcon(R.drawable.ic_baseline_arrow_back);
        toolbar.setNavigationOnClickListener(view -> finish());
        toolbar.setOnMenuItemClickListener(item -> {
            switch (item.getGroupId()){
                case 0:
                case 1:
                case 2:
                case 3:{
                    Toast.makeText(cuttingReceive.this, "点了一下"+item.getTitle(), Toast.LENGTH_SHORT).show();
                    break;
                }
            }
            return false;
        });

        //listView获取点击数据
        listView.setOnItemClickListener((adapterView, view, i, l) -> {
            //当不是第一行时才弹窗
            if(i != 0)
            {
                HashMap<String,String> map = (HashMap<String,String>)listView.getItemAtPosition(i);
                getListData(map,i);//传行数
            }
        });

        //提交按钮
        button.setOnClickListener(view -> {
            Gson gson = new Gson();
            String json = gson.toJson(list);//利用json防止全域变量跟住改变
            try {
                summit(json);
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
        });

        //广播回调
        mBroadcastReceiver.setScanHeadListener(getcode -> {
            mBroadcast(getcode);
        });

        //数据库回调
        handlePublic.setGetResult((what, t) -> GetResult(what,t));

    }

    private void mBroadcast(String code)
    {

        switch(code.substring(0,2))
        {
            case "WO":
                EditText editText = findViewById(R.id.CQNum);
                editText.setText(code);
                EditText editText1 = findViewById(R.id.cangku);
                String cWhCode = editText1.getText().toString();
                HashMap<String,String> hashMap = new HashMap<>();
                hashMap.put("barcode",code);
                // hashMap.put("cWhCode",cWhCode);
                String josn = handlePublic.MakeJson(hashMap);
                System.out.println(josn);
                //handlePublic.startLoad(cuttingReceive.this);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        CommSelectMethod(Action.action.GetBarcode,josn,CQREV);
                    }
                }).start();
                break;
            case "EM":
               // handlePublic.startLoad(cuttingReceive.this);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        CommSelectMethod(Action.action.GetPerson,code,Pr);
                    }
                }).start();
                break;

        }
    }

    //获取点击后的listView数据放进实体类
    private void getListData(HashMap<String,String> map,int i)
    {
        if (!map.isEmpty())
        {
            myListView.cMatNo = map.get("物料编码");
            myListView.cSpecifution = map.get("规格型号");
            myListView.cBatchNumber = map.get("出厂编号");
            myListView.dWidth = map.get("宽度(mm)");
            myListView.dLength = map.get("长度(mm)");
            myListView.dPlanQty = map.get("片数");
            myListView.ddz = map.get("单重");
            myListView.rkWeight = map.get("重量(kg)");
            myListView.cPosCode = map.get("库位");
            myListView.cCateNo = map.get("物料大类");
            setUpdateDialog(i);
        }
        else
        {
            handlePublic.Alert("表格为空，请获取流传单信息",this);
        }
    }

    /**
     * 弹窗
     * @param i
     */
    private void setUpdateDialog(int i) {

        final Dialog dialog = new Dialog(cuttingReceive.this);
        dialog.setContentView(R.layout.activity_dialog_update);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
        dialogWindow.setAttributes(lp);
        final  EditText editText = dialog.findViewById(R.id.cMatNo1);
        final  EditText editText1 = dialog.findViewById(R.id.cSpecifution1);
        final  EditText editText2 = dialog.findViewById(R.id.cBatchNumber1);
        final  EditText editText3 = dialog.findViewById(R.id.dWidth1);
        final  EditText editText4 = dialog.findViewById(R.id.dLength1);
        final  EditText editText5 = dialog.findViewById(R.id.dPlanQty1);
        final  EditText editText6 = dialog.findViewById(R.id.ddz1);
        final  EditText editText7 = dialog.findViewById(R.id.rkWeight1);
        final  EditText editText8 = dialog.findViewById(R.id.cPosCode1);
        final  EditText editText9 = dialog.findViewById(R.id.cCateNo1);
        Button btnConfirm = dialog.findViewById(R.id.submit4);
        Button btnCancel = dialog.findViewById(R.id.submit3);
        editText.setText(myListView.cMatNo);
        editText1.setText(myListView.cSpecifution);
        editText2.setText(myListView.cBatchNumber);
        editText3.setText(myListView.dWidth);
        editText4.setText(myListView.dLength);
        editText5.setText(myListView.dPlanQty);
        editText6.setText(myListView.ddz);
        editText7.setText(myListView.rkWeight);
        editText8.setText(myListView.cPosCode);
        editText9.setText(myListView.cCateNo);

        //禁止手动编辑
        editText.setEnabled(false);
        editText1.setEnabled(false);
        editText2.setEnabled(false);
        editText3.setEnabled(false);
        editText4.setEnabled(false);
        editText5.setEnabled(false);
        editText6.setEnabled(false);
        dialog.show();

        //表单判断没写
        btnConfirm.setOnClickListener(view -> {
            myListView.rkWeight = editText7.getText().toString();
            myListView.cPosCode = editText8.getText().toString();
            myListView.cCateNo = editText9.getText().toString();
            list.get(i).replace("重量(kg)",myListView.rkWeight);
            list.get(i).replace("库位",myListView.cPosCode);
            list.get(i).replace("物料大类",myListView.cCateNo);
            dialog.dismiss();
            listView.setAdapter(null);
            setadapter();
        });
        //弹窗取消按钮
        btnCancel.setOnClickListener(view -> dialog.dismiss());
    }


    //数据库回调数据处理
    private void GetResult(int what,Object t) throws JSONException {
        EditText editText1 = findViewById(R.id.CQNum);
        EditText editText2 = findViewById(R.id.Person);
        String ret = handlePublic.dealDataBase((List)t);
        if (ret.contains("[") || ret.contains("{"))
        {
            switch (what)
            {
                case CQREV://裁切接收查询回调
                    jsonArray = new JSONArray(ret);
                    setListView(jsonArray);
                    break;
                case SREV://裁切接收提交回调
                    handlePublic.Alert("提交成功",this);
                    editText1.setText("");
                    editText2.setText("");
                    list.clear();
                    setadapter();
                    break;
                case Pr://人员回调
                    Person person = (Person) handlePublic.getEntity(ret,Person.class);
                    Action.person = person;
                    editText2.setText(Action.person.cPsn_Name);
            }
        }else
        {
            handlePublic.Alert(ret,this);
        }
    }

    //通用的数据库查询方法
    private void CommSelectMethod(String action,String para,int what) {

        List BList;
        if (para.startsWith("EQ") || para.startsWith("EM"))//如果参数为查找人员或设备
        {
            if (para.startsWith("EM"))
            {
                para =para.split("-")[1];
            }
            Net_userData net_userData = new Net_userData();
            BList = net_userData.User_CommonMethod(action,para);
        }else
        {
            BList = dbUtil.CRC_CommonMethod(action,para);
        }
        handlePublic.setmHandler(what,BList);
    }


    private void setListView(JSONArray jsonArray) throws JSONException {
        listView.setVisibility(View.VISIBLE);
        //若执行重复 要将list清除
        if (!list.isEmpty())
        {
            list.clear();
        }
        getAllInfo(jsonArray);
        setadapter();
    }


    private List<HashMap<String, String>> getAllInfo(JSONArray jsonArray) throws JSONException {
        HashMap<String, String> tempHash = new HashMap<String, String>();
        tempHash.put("物料编码", "物料编码");
        tempHash.put("规格型号", "规格型号");
        tempHash.put("出厂编号", "出厂编号");
        tempHash.put("宽度(mm)", "宽度(mm)");
        tempHash.put("长度(mm)", "长度(mm)");
        tempHash.put("片数", "片数");
        tempHash.put("单重", "单重");
        tempHash.put("重量(kg)", "重量(kg)");
        tempHash.put("库位", "库位");
        tempHash.put("物料大类", "物料大类");
        list.add(tempHash);

        for (int j = 0; j < jsonArray.length(); j ++) {
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("物料编码", jsonArray.getJSONObject(j).get("cMatNo").toString());
            hashMap.put("规格型号", jsonArray.getJSONObject(j).get("cSpecifution").toString());
            hashMap.put("出厂编号", jsonArray.getJSONObject(j).get("cBatchNumber").toString());
            hashMap.put("宽度(mm)", jsonArray.getJSONObject(j).get("dWidth").toString());
            hashMap.put("长度(mm)", jsonArray.getJSONObject(j).get("dLength").toString());
            hashMap.put("片数", jsonArray.getJSONObject(j).get("dPlanQty").toString());
            hashMap.put("单重", jsonArray.getJSONObject(j).get("ddz").toString());
            hashMap.put("重量(kg)", "");
            hashMap.put("库位", jsonArray.getJSONObject(j).get("cPosCode").toString());
            hashMap.put("物料大类", jsonArray.getJSONObject(j).get("cCateNo").toString());
            list.add(hashMap);
        }
        return list;
    }


    //提交逻辑
    private void summit(String json) throws JSONException {
        EditText editText = findViewById(R.id.cangku);
        if (json.equals("[]"))
        {
            handlePublic.Alert("表格数据为空",this);
        }else
        {
            //提交时增加提交需要的数据
            List<HashMap<String,String>> list1 = new ArrayList<>();
            for (int i = 0; i < jsonArray.length(); i++)
            {
                HashMap<String,String> hashMap = new HashMap<>();
                hashMap.put("cMatNo1",jsonArray.getJSONObject(i).get("cMatNo1").toString());
                hashMap.put("dReqQty",jsonArray.getJSONObject(i).get("dReqQty").toString());
                hashMap.put("cMOLotNo",jsonArray.getJSONObject(i).get("cMOLotNo").toString());
                hashMap.put("cOrderNo",jsonArray.getJSONObject(i).get("cOrderNo").toString());
                hashMap.put("dProductDate",jsonArray.getJSONObject(i).get("dProductDate").toString());
                hashMap.put("cSupplierInfo",jsonArray.getJSONObject(i).get("cSupplierInfo").toString());
                hashMap.put("cProductDepNo",jsonArray.getJSONObject(i).get("cProductDepNo").toString());
                hashMap.put("warehousecode",editText.getText().toString());//仓库
                list1.add(hashMap);
            }
            Gson gson = new Gson();
            String list1Json = gson.toJson(list1);
            json = handlePublic.JosnChange(json);
            list1Json = handlePublic.JosnChange(list1Json);
            JSONArray jsonArray1 = new JSONArray(json);
            jsonArray1.remove(0);
            JSONArray jsonArray2 = new JSONArray(list1Json);
            jsonArray1.put(jsonArray2);
           // handlePublic.startLoad(cuttingReceive.this);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    List<String> list2 = new ArrayList<>();
                    list2 = dbUtil.CRC_CommonMethod(Action.action.CRC_Summit,jsonArray1.toString());//提交到数据库
                    handlePublic.setmHandler(SREV,list2);
                }
            }).start();
            System.out.println(jsonArray1.toString());
        }
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_menu, menu);
        //MenuItem menuItem = menu.findItem(R.id.toolbar_user);
        //menuItem.setVisible(false);
        setVisible(true);
        return true;
    }

    @Override
    public void onBackPressed() {
        if (mReceiverTag) {
            unregisterReceiver(mBroadcastReceiver);
            finish();
        }
    }

    //写listView
    private void setadapter()
    {
        adapter = new SimpleAdapter(
                cuttingReceive.this,
                list,
                R.layout.activity_main3,
                new String[] { "物料编码", "规格型号","出厂编号","宽度(mm)","长度(mm)","片数","单重","重量(kg)","库位","物料大类"},
                new int[] { R.id.cMatNo, R.id.cSpecifution,R.id.cBatchNumber,R.id.dWidth,R.id.dLength,R.id.dPlanQty,R.id.ddz,
                        R.id.rkWeight,R.id.cPosCode,R.id.cCateNo});
        listView.setAdapter(adapter);
    }

//    private void Alert(String Message)
//    {
//        AlertDialog.Builder builder = new AlertDialog.Builder(cuttingReceive.this);
//        builder.setTitle("信息");
//        builder.setMessage(Message);
//        builder.setNegativeButton("确定",
//                (dialog, which) -> dialog.dismiss());
//        builder.create().show();
//    }
}